/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import service.Audio;
import service.PhotoCollection;
import service.Planet;
import service.PlanetFacadeREST;
import service.Video;

/**
 *
 * @author andrew
 */
public class manageDescriptionServlet extends HttpServlet {

    @EJB
    private PlanetFacadeREST planetManager;

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //HttpSession session = request.getSession();
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }
        
        
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        //String description = request.getParameter("description");
        // ottieni id Universo e id pianeta
        
        //Integer universe_id = (Integer)session.getAttribute("idUniverse");
        Integer planet_id = (Integer)session.getAttribute("idPlanet");
        // valore di happiness
        Integer happiness_session = Integer.parseInt(request.getParameter("happiness"));
        String typeObject = request.getParameter("type");
        System.out.println("!!!DESCRIPTION Servlet GET happiness a: " + happiness_session);
        
        String desc = "";
        String title = "";
        

        boolean isHappy=true;

        if(happiness_session == 0) {
            isHappy = false;
        }
        
        
        if(typeObject.equals("image")){
            // parte IMMAGINI
            
            Planet planet = planetManager.find(planet_id);
            Collection<PhotoCollection> collPhotoColl = planet.getPhotoCollectionCollection();
            Iterator<PhotoCollection> itColl = collPhotoColl.iterator();
            while(itColl.hasNext()){
                PhotoCollection p = itColl.next();
                if(p.getIsHappy() == isHappy){
                    desc = p.getDescription();
                }
            }
            
        }else{
            // parte MULTIMEDIA
            Planet planet = planetManager.find(planet_id);
                
            Collection<Audio> collAudio = planet.getAudioCollection();
            Collection<Video> collVideo = planet.getVideoCollection();

            if( (collAudio != null) ){
                Iterator itAudio = collAudio.iterator();
                while(itAudio.hasNext()){
                    Audio a = (Audio) itAudio.next();
                    if(a.getIsHappy() == isHappy){
                        desc = a.getDescription();
                        title = a.getTitle();
                    }
                }
            }

            if( (collVideo != null) ){
                Iterator itVideo = collVideo.iterator();
                while(itVideo.hasNext()){
                    Video v = (Video) itVideo.next();
                    if(v.getIsHappy() == isHappy){
                        desc = v.getDescription();
                        title = v.getTitle();
                    }
                }
            }
        }
        
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("desc", desc);
        jsonObject.addProperty("title", title);
        
        out.print(jsonObject);
        out.close();
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     
        //HttpSession session = request.getSession();
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }
        
        //ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
        
        
        String description = request.getParameter("description");
        System.out.println("Valore di description: "+description);
        String title = request.getParameter("title");
        System.out.println("Valore di title: "+title);
        
         //new String(latin1, "ISO-8859-1").getBytes("UTF-8");    
        // ottieni id Universo e id pianeta
        
        //Integer universe_id = (Integer)session.getAttribute("idUniverse");
        Integer planet_id = (Integer)session.getAttribute("idPlanet");
        // valore di happiness
        Integer happiness_session = Integer.parseInt(request.getParameter("happiness"));
        System.out.println("!!!DESCRIPTION Servlet POST settato happiness a: " + happiness_session);
        
        String typeObject = request.getParameter("type");
        
        String desc= "";
        
        if(typeObject.equals("image")){
            // modifico description immagine
            if(description != null && !ServletFileUpload.isMultipartContent(request)){
                // in questo caso si ha cliccato su una tab, aggiorno solo decription
                System.out.println("DENTRO! description:"+description);

                boolean isHappy=true;
                if(happiness_session == 0) {
                    isHappy = false;
                }

                Planet planet = planetManager.find(planet_id);
                Collection<PhotoCollection> collPhotoColl = planet.getPhotoCollectionCollection();
                if(!description.equals("")){
                    Iterator<PhotoCollection> itColl = collPhotoColl.iterator();
                    while(itColl.hasNext()){
                        PhotoCollection p = itColl.next();
                        
                        if(p.getIsHappy() == isHappy){
                            p.setDescription(description);
                        }
                    }
                    planet.setPhotoCollectionCollection(collPhotoColl);
                    planetManager.edit(planet);
                }
                    
                
                
            }
        }else if(typeObject.equals("multimedia")){
            // modifico description multimediale
            if(description != null && !ServletFileUpload.isMultipartContent(request)){
                
                boolean isHappy=true;
                if(happiness_session == 0) {
                    isHappy = false;
                }
                
                Planet planet = planetManager.find(planet_id);
                
                Collection<Audio> collAudio = planet.getAudioCollection();
                Collection<Video> collVideo = planet.getVideoCollection();
                
                if( (collAudio != null) ){
                    Iterator itAudio = collAudio.iterator();
                    while(itAudio.hasNext()){
                        Audio a = (Audio) itAudio.next();
                        if(a.getIsHappy() == isHappy){
                            a.setDescription(description);
                            if(title != null)
                                a.setTitle(title);
                        }
                    }
                    planet.setAudioCollection(collAudio);
                    planetManager.edit(planet);
                }
                
                if( (collVideo != null) ){
                    Iterator itVideo = collVideo.iterator();
                    while(itVideo.hasNext()){
                        Video v = (Video) itVideo.next();
                        if(v.getIsHappy() == isHappy){
                            v.setDescription(description);
                            if(title != null)
                                v.setTitle(title);
                        }
                    }
                    planet.setVideoCollection(collVideo);
                    planetManager.edit(planet);
                }
                
                
            }
        }
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
